<template>
    <div>
        <el-row :gutter="70">
            <el-col :span="8" v-for="(fileIdOfImg,index) in fileIdOfImgArr">
                <div 
                class="img-box">

                    <el-image 
                    class="img-uploaded"
                    :src="$kt.file.visit(fileIdOfImg)"
                    fit="contain"
                    :preview-src-list="getPreviewSrcList()"
                    alt="点击修改" style="width: 100px; height: 100px;"></el-image>
                    <el-row>
                        <!-- 左移 -->
                        <el-col :span="8">
                            <span
                            class="img-box-btn"
                            @click="leftMove(index)"
                            >
                                    <el-icon><CaretLeft /></el-icon>
                            </span>
                        </el-col>

                        <!-- 右移 -->
                        <el-col :span="8">
                            <span
                            class="img-box-btn"
                            @click="rightMove(index)"
                            >
                                    <el-icon><CaretRight /></el-icon>
                            </span>
                        </el-col>

                        <!-- 删除 -->
                        <el-col :span="8">
                            <span
                            class="img-box-btn"
                            style="color: red;
                            text-align: right;
                            "
                            @click="deleteImg(index)"
                            >
                                    <el-icon><Delete /></el-icon>
                            </span>
                        </el-col>

                    </el-row>

                </div>

            </el-col>
        </el-row>

        <input type="file" :id="fileIdInputId" style="display: none;" @change="fileChange($event)" />
        <el-button @click="fileClick()" type="text">添加</el-button>

        <div>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </div>

</div>
</template>

<script lang="ts" setup>
import { ref, defineEmits, defineExpose,defineProps,onMounted, watch } from 'vue';
import $kt from '@/vueKantboot';
import { ElLoading, ElMessage } from 'element-plus'

let emits = defineEmits(['change']);

let props = defineProps({
    fileIdOfImgArr: {
        type: String||Array,
        default: '[]',
    }
})
let fileIdOfImgArr = ref([]);

onMounted(() => {
    // 如果传入的是字符串，转换成数组
    if(typeof props.fileIdOfImgArr == 'string'){
        fileIdOfImgArr.value = JSON.parse(props.fileIdOfImgArr);
        console.log(fileIdOfImgArr.value);
    }else{
        fileIdOfImgArr.value = props.fileIdOfImgArr;
    }
})

// 监听props.value的变化
watch(() => props.fileIdOfImgArr, (newVal) => {
    if(typeof newVal == 'string'){
        fileIdOfImgArr.value = JSON.parse(newVal);
    }else{
        fileIdOfImgArr.value = newVal;
    }
})

let dialogVisible = ref(false);

let isFileUploading = ref(false);


let fileIdInputId = ref("");

let createFileIdInputId = () => {
    let uuid = "";
    for (let i = 0; i < 32; i++) {
        uuid += Math.floor(Math.random() * 16).toString(16);
    }
    fileIdInputId.value = "file" + uuid;
}

createFileIdInputId();

let fileClick = () => {
    document.getElementById(fileIdInputId.value)?.click();
}

let emitsChange = () => {
    emits("change",{
        arr: fileIdOfImgArr.value,
        str: JSON.stringify(fileIdOfImgArr.value),
    });
}

let fileChange = async (event: any) => {
    let file = event.target.files[0];
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    isFileUploading.value = true;

    // TODO: 上传图片
    const response = await $kt.request.upload({
        data: {
            file: file,
            groupCode: 'goodsType'
        },
    }).then((res: any) => {
        if (res.data.success) {
            ElMessage({
                message: '上传成功',
                type: 'success',
            })

            // 给图片id赋值
            fileIdOfImgArr.value.push(res.data.data.id);

            emitsChange();

            isFileUploading.value = false;
            loading.close();
            return false;
        }
        isFileUploading.value = false;
        loading.close();
        ElMessage({
            message: res.data.errMsg,
            type: 'error',
        });


    })
}


let leftMove = (index: number) => {
    if (index == 0) {
        return false;
    }
    let temp = fileIdOfImgArr.value[index];
    fileIdOfImgArr.value[index] = fileIdOfImgArr.value[index - 1];
    fileIdOfImgArr.value[index - 1] = temp;
    emitsChange();
}

let rightMove = (index: number) => {
    if (index == fileIdOfImgArr.value.length - 1) {
        return false;
    }
    let temp = fileIdOfImgArr.value[index];
    fileIdOfImgArr.value[index] = fileIdOfImgArr.value[index + 1];
    fileIdOfImgArr.value[index + 1] = temp;
    emitsChange();
}

let deleteImg = (index: number) => {
    fileIdOfImgArr.value.splice(index, 1);
    emitsChange();
}


let getPreviewSrcList = () => {
    let previewSrcList: string[] = [];
    for (let i = 0; i < fileIdOfImgArr.value.length; i++) {
        previewSrcList.push($kt.file.visit(fileIdOfImgArr.value[i]));
    }
    return previewSrcList;
}


</script>


<style lang="scss" scoped>

.img-box{
    position: relative;
    width: 100px;
    border-radius: 5px;
    margin-bottom: 10px;
    padding: 5px;
    box-shadow: 0px 0px 5px 0px rgba(118,118,118,0.2);

    .img-uploaded{
        cursor: pointer;
        border-radius: 5px;
    }
}

.img-box .el-image{
    width: 100%;
    height: 100%;
}

.img-box-btn{
    cursor: pointer;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

</style>